from selenium import webdriver
from selenium.webdriver.common.by import By
import datetime
import time

# 自动打开浏览器并且最大化窗口
driver = webdriver.Chrome()
driver.maximize_window()





step = 0


def updateStep():
    global step
    if step == 1:
        try:
            if driver.find_element(By.LINK_TEXT, '亲，请登录'):
                step = 2
        except:
            1
    elif step == 3:
        try:
            if driver.find_element(By.CLASS_NAME, "member-delivery"):
                step = 4
        except:
            1
            # print("wait to step 4")
    elif step == 5:
        try:
            if driver.find_element(By.ID, 'J_Go'):
                step = 6
        except:
            1
   
    elif step == 9:#等待进入有提交订单按钮的界面
        try:
            if driver.find_element(By.CLASS_NAME, "go-btn"):
                step = 10
        except:
            1
    elif step == 11:
        try:
            if driver.find_element(By.ID, 'err') and driver.find_element(By.CLASS_NAME, 'reason-list'):
                step = 12
        except:
            try:
                if  driver.find_element(By.XPATH, "//span[text()='其他方式付款']") and driver.find_element(By.XPATH, "//span[text()='海外地区方式付款']"):
                    step = 13
            except:
                1


def steping():
    global step
    if step == 0:
        driver.get('https://www.taobao.com')
        step += 1
    elif step == 2:
        driver.find_element(By.LINK_TEXT, '亲，请登录').click()
        step += 1
    elif step == 4:#登入成功打开购物车
        driver.get("https://cart.taobao.com/cart.htm")
        step += 1
    elif step == 6:#购物车界面已经完全展示
        print("请10s内勾选要购买的商品")
        time.sleep(10)
        step += 1
    elif step == 7:#输入抢购时间并等待时间的到来
        now = datetime.datetime.now()
        print("当前时间 ", now.strftime("%Y-%m-%d %H:%M:%S"))
        buy_times = input("请输入抢购时间(例如格式：2022-08-17 21:00:00):")
        targetTime = time.mktime(time.strptime(buy_times, "%Y-%m-%d %H:%M:%S"))
        while time.time() < targetTime:
            print("等待时间到来")
            time.sleep(0.001)
        step += 1
    elif step == 8:#购买
        driver.find_element(By.ID, 'J_Go').click()
        step += 1
    elif step == 10:#提交订单
        step += 1
        driver.find_element(By.CLASS_NAME, "go-btn").click()
        print('提交订单')
        # return 1
    elif step == 12:#服务器繁忙，返回到提交订单界面
        step = 9
        driver.back()
        print('服务器繁忙，返回到提交订单界面')
    elif step == 13:#抢购成功
        step += 1
        print('抢购成功，请尽快付款')
        return 1
    return 0


if __name__ == "__main__":
    while 1:
        updateStep()
        result = steping()
        if result == 1:
            break
        time.sleep(0.001)

    while 1:
        time.sleep(1)
